<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/17 0017
 * Time: 下午 2:22
 */
namespace App\Api\Service\Customer\Controllers;

use App\Eloquent\Ygt\CustomerOrder;
use App\Eloquent\Ygt\SaleCompanyRelation;
use App\Eloquent\Ygt\User;
use App\Engine\Buyers;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Customer;
use App\Eloquent\Ygt\CustomerInvoice;
use App\Engine\Func;
use App\Eloquent\Ygt\DepartmentUser;
use App\Engine\Customer as CustomerEngine;
use App\Eloquent\Province;
use App\Eloquent\City;
use App\Eloquent\Area;

use App\Eloquent\Ygt\CustomerBuyer;


class IndexController extends Controller
{
    protected $isSalesperson;
    public $userId      = 25;

    public function getList(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : 5;

        $customerModel = new Customer();
        $where = [
            'company_id'=>$companyId,'add_user_id'=>$userId
        ];
        if($customerName = request('customer_name')){
            $where['customer_name'] = ['like','%'.$customerName.'%'];
        }
        if($salesUid = request('sales_uid')){
            $where['sales_uid'] = $salesUid;
        }
        if($customerLevel = request('customer_level')){
            $where['customer_level'] = $customerLevel;
        }

        //新加单位限制
        if($customerName = request('company_name')){
            $where['company_name'] = $customerName;
        }

        $fields = '*';

        $page = request('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $result = $customerModel->getData($where, $fields, $limit, $offset);

        $list = $result->map(function($item, $key){
           /* $tmp = [
                'id'=>$item->id,
                'customer_name'=>$item->customer_name,
                'customer_no'=>$item->customer_no,
                'customer_tel'=>$item->customer_tel,
                'customer_address'=>$item->customer_address,
                'contact_person'=>$item->contact_person,
                'contact_phone'=>$item->contact_phone,
                'contact_address'=>$item->contact_address,
                'sales_name'=>$item->sales->truename,
                'sales_uid'=>$item->sales_uid,
                'last_order_time'=>$item->last_order_time,
            ];*/
            return $this->composeInfo($item);
        })->toArray();
        $count = $customerModel->getCount($where);

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($list, $pagingData);


    }

    public function getAllListWithLetter()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        if(!$userInfo)
        {
            xThrow( ERR_PARAMETER,'登录超时' );
        }
        $companyId          = $userInfo->company_id;

        //判断用户是否为销售员（销售员才有权限下订单）
        $privilegeId        = $userInfo->privilege_id;;
        $isSalesperson      = \App\Eloquent\Ygt\Privilege::getAppnodeId($privilegeId, 13);//是否为销售员
        if($isSalesperson){
            $this->isSalesperson = 1;
        }else{
            $this->isSalesperson = 0;
        }
        //取客户列表
        $customerModel      = new Customer();
        $where              = [ 'company_id'=>$companyId ];
        //如果不是下单人，只显示自己添加的用户
        $privilegeIdList    = \App\Engine\OrderEngine::getPrivilegeByNode($companyId,1);
        if(!in_array($privilegeId,$privilegeIdList)){
            //如果传入参数is_all=1显示所有用户,主要解决采购员添加材料展示客户列表问题
            $isAll = request('is_all');
            if($isAll != 1){
                $where['add_user_id']   = $userId;
            }
        }



        /************筛选**********/
        $customerLevel      = request('customer_level',0);
        if($customerLevel)
        {
            $where['customer_level']    = $customerLevel;
        }
        //新加单位限制
        $companyName        = request('company_name','');
        if($companyName)
        {
            $custmerIds     = CustomerBuyer::where(['buyer_id'=>$companyName])->get()->pluck('customer_id');
            $where['id']    = ['in',$custmerIds];
        }
        /**********筛选结束************/
        $keyword            = request('keyword','');
        if($keyword){
            $where['customer_name']     = ['like','%'.$keyword.'%'];
            $groupby        = $customerModel->getData($where);
            //单位搜索
            $buyerIds       = \App\Eloquent\Ygt\Buyers::where([['buyer_name','like','%'.$keyword.'%'],['company_id','=',$companyId]])->get()->pluck('id');
            $custmerIds     = CustomerBuyer::whereIn('buyer_id',$buyerIds)->get()->pluck('customer_id');
            $where2['id']   = ['in',$custmerIds];
            $groupby2       = $customerModel->getData($where2);
            //合并数据
            $ids1           = $groupby->pluck('id');
            foreach ($groupby2 as $tmpRow){
                if(!in_array($tmpRow->id,$ids1->toArray())){
                    $groupby->push($tmpRow);
                }
            }
        }else{
            $groupby        = $customerModel->getData($where);
        }
        //是否有权限创建订单
        $groupby            = $groupby->map(function($item){
            if($this->isSalesperson){
                $item['able_create_customer_order'] = 1;
                $item['able_create_receivable'] = 1;
            }else{
                $item['able_create_customer_order'] = 0;
                $item['able_create_receivable'] = 0;
            }
            return $item;
        });
        $groupby            = $groupby->map(function($item){
            return $this->composeInfo($item);
        })->groupBy('first_letter');
        return $groupby->map(function($item, $key){
            //新加字段
            return collect([
                'letter'=>$key,
                'list'=>$item
            ]);
        })->sortBy('letter')->values();
    }

    public function getInfo(){
        $where = [
            'id'=>request('id')
        ];
        $rules = [
            'id' => 'required|integer',
        ];
        $this->validateRequestParameters($where, $rules);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $where['company_id'] = $companyId;

        $customerModel = new Customer();
        if($item = $customerModel->getOneData($where)){
            $info = $this->composeInfo($item);

            //追加地址详情
            $info['customer_detail_address'] = $info['customer_address'];
            if($info['province_name'] && $info['city_name'] && $info['area_name']){
                $info['customer_detail_address'] = $info['province_name'].'-'.$info['city_name'].'-'.$info['area_name'].'-'.$info['customer_detail_address'];
            }

            //追加单位信息
            $customerId = $info['id'];
            $where = ['customer_id'=>$customerId];
            $customerBuyerList = CustomerBuyer::where($where)->get();

            $buyerList = [];
            foreach ($customerBuyerList as $customerBuyerRow){
                $buyerId = $customerBuyerRow['buyer_id'];
                $buyerList[] = Buyers::getNameById($buyerId);
            }
            $info['buyerList'] = $buyerList;

            return $info;
        }else{
            xThrow(ERR_CUSTOMER_IS_NOT_EXIST);
        }
    }

    private function composeInfo($item)
    {
        $Letters = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        //单位名称需特殊处理下
        $buyersIds = $item->company_name;
        $companyName = '';
        if($buyersIds){
            $buyersIdList = explode(',',$buyersIds);
            foreach ($buyersIdList as $buyersId){
                $tmpCompanyName = Buyers::getNameById($buyersId);
                if($tmpCompanyName){
                    $companyName .= $tmpCompanyName.',';
                }
            }

            $companyName = substr($companyName,0,-1);
        }

        $tmp = [
            'id'=>$item->id,
            'customer_name'=>$item->customer_name,
            'company_name'=>$companyName,
            'payment_days'=>$item->payment_days,
            'credit_amount'=>$item->credit_amount,
            'company_ids'=>$item->company_name,
            'first_letter'=>in_array($item->first_letter,$Letters)?$item->first_letter:'#',
            'customer_no'=>$item->customer_no,
            'avatars_id'=>$item->avatars_id,
            'avatars_url'=>Func::getImgUrlById($item->avatars_id),
            'customer_level'=>$item->customer_level,
            'customer_level_title'=>CustomerEngine::getLevelTitle($item->customer_level),
            'customer_tel'=>$item->customer_tel,
            'short_customer_tel'=>$item->short_customer_tel,
            'customer_address'=>$item->customer_address,
            'contact_person'=>$item->contact_person,
            'contact_phone'=>$item->contact_phone,
            'contact_address'=>$item->contact_address,
            'sales_uid'=>$item->sales_uid,
            'sales_name'=>$item->sales_name,
            'sales_mobile'=>$item->sales_mobile,
//            'sales_name'=>isset($item->sales->truename)?$item->sales->truename:'',
            'merchandiser_uid'=>$item->merchandiser_uid,
//            'merchandiser_name'=>isset($item->merchandiser->truename)?$item->merchandiser->truename:'',
            'merchandiser_name'=>$item->merchandiser_name,
            'province_id'=>$item->province_id,
            'city_id'=>$item->city_id,
            'area_id'=>$item->area_id,
            'province_name'=>$item->province_name,
            'city_name'=>$item->city_name,
            'area_name'=>$item->area_name,
            'reg_mobile'=>$item->reg_mobile,
            'last_order_time'=>$item->last_order_time?date('Y-m-d',$item->last_order_time):'无',
            'able_create_customer_order'=>$item->able_create_customer_order,
            'able_create_receivable'=>$item->able_create_receivable,
            'settlement_method'=>$item->settlement_method,
            'is_add_order'=>$item->is_add_order,
        ];

        $customerId             = $item->id;
        //应收款
        $where                  = [
            ['customer_id','=',$customerId],
            ['status','=',0]
        ];
        $totalMoney             = \App\Eloquent\Ygt\WarehouseBill::where($where)->sum('now_money');
        $totalMoneyTxt          = $totalMoney!= 0 ? '¥ '.$totalMoney : '无';
        $tmp['total_money']     = $totalMoneyTxt;
        //最近收款
        $where                  = [
            ['customer_id','=',$customerId],
            ['table','=','warehouse_bill'],
        ];
        $lastMoney              = \App\Eloquent\Ygt\BillLog::where($where)->value('money');
        $lastMoneyTxt           = $lastMoney!= 0 ? '¥ '.$lastMoney : '无';
        $tmp['last_money']   = $lastMoneyTxt;
        $where                = ['customer_name'=>$item->id];
        $lastOrder            = CustomerOrder::where($where)->orderByDesc('id')->first();
        $lastOrderTxt        = '无';
        if($lastOrder)
        {
            $lastOrderArr       = $lastOrder->toArray();
            $createdAt          = $lastOrderArr['created_at'];
            $productNum         = $lastOrderArr['product_num'];
            $productNumArr      = explode(',',$productNum);
            $productNumStr      = '';
            if( is_array($productNumArr) && !empty($productNumArr[0]))
            {
                $productNumStr  = $productNumArr[0].$productNumArr[1];
            }
            $lastOrderTxt      = date('Y-m-d',$createdAt);
            $lastOrderTxt      .= ' '.$productNumStr;
        }
        $tmp['last_order']   = $lastOrderTxt;
//        $tmp['remind']       = ['下单预警','收款预警'];
        $tmp['remind']       = [];
        return $tmp;
    }

    public function addBefore()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        if( !$userId )
        {
            xThrow( ERR_PARAMETER );
        }
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $result             = [
            'truename'=>$userInfo['truename'],
            'mobile'=>$userInfo['mobile'],
        ];
        return $result;
    }
    public function customerAdd()
    {
        $headerUserId       = Func::getHeaderValueByName( 'userid',$this->userId);
        $headerUserInfo     = DepartmentUser::getCurrentInfo( $headerUserId );
        $data               = request()->all();
        if( !$headerUserInfo )
        {
            xThrow( ERR_PARAMETER,'登录过期' );
        }
        $companyId          = $headerUserInfo->company_id;
        //检测关联账号 在该厂 是否已经添加过
        $regMobile          = request('reg_mobile',0);
        $customerName       = request('customer_name','');
        $mobilePreg         = '/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/';
        $mobilePreg         = '/^\d{11}$/';
        $mobilePregResult   = preg_match( $mobilePreg, $regMobile );
        if(!$mobilePregResult)
        {
            xThrow( ERR_PARAMETER,'关联账号手机号格式不正确' );
        }
        $where              = ['reg_mobile'=>$regMobile,'company_id'=>$companyId];
        $info               = Customer::getInfo($where);
        if($info)
        {
            xThrow( ERR_PARAMETER,'你已经添加过该客户了');
        }
        //关联账号问题,不存在则注册为用户,存在则取对应的用户id
        $registerResult     = User::registerByType($regMobile,$customerName,1);
        $registerStatus     = $registerResult['status'];
        $registerUserId     = $registerResult['user_id'];
        $registerMessage    = $registerResult['message'];
        //$registerStatus 0失败,1不存在插入成功,2已存在取值成功
        if($registerStatus == 1){
            //若是新注册的则需插入的员工表,,注意这时的厂id是特殊的
            $saleArr                = config('ygt.sale_arr');
            $registerCompanyId      = $saleArr['company_id'];
            $privilegeId            = $saleArr['privilege_id'];
            $departmentUserData     = [
                'user_id'=>$registerUserId,
                'company_id'=>$registerCompanyId,
                'privilege_id'=>$privilegeId,
                'mobile'=>$regMobile,
                'truename'=>$customerName,
            ];
            DepartmentUser::insertOneData( $departmentUserData );
        }else if($registerStatus == 2){
            //暂时不需要做处理
        }else{
            xThrow(ERR_PARAMETER, $registerMessage);
        }
        //提交的数据做一下处理,主要针对,添加和编辑时一样的数据
        $data                   = $this->transformData($data);
        //其它信息
        $data['company_id']     = $companyId;
        $data['reg_mobile']     = $regMobile;//关联账号
        $data['user_id']        = $registerUserId;//关联账号对应的用户id
        $data['add_user_id']    = $headerUserId;//添加该客户的人的用户id
        //插入客户表
        $fieldList              = Customer::$tableFieldList;
        $tableData              = Customer::setDataByTableField($data,$fieldList);
        $tableDataCheckResult   = Customer::checkDataByTableField($tableData,$fieldList);
        if($tableDataCheckResult !== true)
        {
            xThrow(ERR_PARAMETER, $tableDataCheckResult);
        }
        $customerId             = Customer::edit($tableData,'id');
        if(!$customerId)
        {
            xThrow(ERR_UNKNOWN, '客户添加失败');
        }
        $result             = ['message'=>'添加成功'];
        return $result;
    }
    public function customerEdit()
    {
        $headerUserId       = Func::getHeaderValueByName( 'userid',$this->userId);
        $headerUserInfo     = DepartmentUser::getCurrentInfo( $headerUserId );
        $data               = request()->all();
        if( !$headerUserInfo )
        {
            xThrow( ERR_PARAMETER,'登录过期' );
        }
        $companyId          = $headerUserInfo->company_id;
        $requestCustomerId  = request('id',0);
        if(!$requestCustomerId)
        {
            xThrow( ERR_PARAMETER);
        }
        $where                  = ['id'=>$requestCustomerId];
        $oldCustomer            = Customer::getInfo($where);
        if(!$oldCustomer)
        {
            xThrow( ERR_PARAMETER);
        }
        $oldUserId              = $oldCustomer->user_id;
        //提交的数据做一下处理,主要针对,添加和编辑时一样的数据
        $data                   = $this->transformData($data);
        $data['company_id']     = $companyId;
//        $data['add_user_id']    = $headerUserId;//添加该客户的人的用户id
        $data['add_user_id']    = $oldCustomer->add_user_id;
        $data['user_id']        = $oldUserId;
        //插入客户表
        $fieldList              = Customer::$tableFieldList;
        $tableData              = Customer::setDataByTableField($data,$fieldList);
        $tableDataCheckResult   = Customer::checkDataByTableField($tableData,$fieldList);
        if($tableDataCheckResult !== true)
        {
            xThrow(ERR_PARAMETER, $tableDataCheckResult);
        }
        $customerId             = Customer::edit($tableData,'id');
        if(!$customerId)
        {
            xThrow(ERR_UNKNOWN, '客户编辑失败');
        }
        $result             = ['message'=>'编辑成功'];
        return $result;
    }
    //客户添加 或 编辑提交数据时,对于同样的的数据做统一处理
    private function transformData($data)
    {
        $provinceName           = $cityName = $areaName = '';
        //省市县处理
        $provinceInfo           = Province::where('provinceID',$data['province_id'])->first();
        if($provinceInfo)
        {
            $provinceName       = $provinceInfo->province;
        }
        $cityInfo               = City::where('cityID',$data['city_id'])->first();
        if($cityInfo)
        {
            $cityName           = $cityInfo->city;
        }
        $areaInfo               = Area::where('areaID',$data['area_id'])->first();
        if($areaInfo)
        {
            $areaName           = $areaInfo->area;
        }
        $data['province_name']  = $provinceName;
        $data['city_name']      = $cityName;
        $data['area_name']      = $areaName;
        $isAddOrder              = isset($data['is_add_order']) ? intval($data['is_add_order']) : 0;
        $data['is_add_order']   = $isAddOrder;
        //首字母
        $pinyin                 = app('pinyin');
        $firstLetter            = strtoupper(substr($pinyin->abbr($data['customer_name']),0,1));
        $data['first_letter']   = $firstLetter;
        return $data;
    }
    /**
     * @return mixed
     * 开票列表
     */
    public function invoiceList(){
        $customerId = request('customer_id');

        $user_id        = Func::getHeaderValueByName( 'userid' );
        $userinfo           = DepartmentUser::getCurrentInfo( $user_id );

        $customerInvoiceModel = new CustomerInvoice();
        $list = $customerInvoiceModel->getData(['company_id'=>$userinfo->company_id,'customer_id'=>$customerId]);

        $return = $list->map(function($item){
            return [
                'id'=>$item->id,
                'customer_id'=>$item->customer_id,
                'title'=>$item->title,
                'taxpayer_number'=>$item->taxpayer_number,
                'address'=>$item->address,
                'telphone'=>$item->telphone,
                'opening_bank'=>$item->opening_bank,
                'bank_card_number'=>$item->bank_card_number,
            ];
        });
        return ($return->toArray());
    }


    /**
     * @return string
     * 客户删除
     */
    public function customerDel()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId);
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $customerId = request('id');
        $where = [
            'id'=>$customerId,
            'company_id'=>$companyId,
        ];
        $customerModel = new Customer();
        if($customerModel->del($where)){
            return 'ok';
        }else{
            xThrow(ERR_CUSTOMER_DELETE_FAIL);
        }

    }

    public function customerLevels(){
        $levels = CustomerEngine::getAllLevel();
        return array_values($levels);
    }

    //客户结算方式，选择列表
    public function getCustomerSettlementMethodList()
    {
        $firstList          = [
            ['id'=>1, 'title'=>'款到发货'],
            ['id'=>2,'title'=>'账期'],
            ['id'=>3, 'title'=>'分期付款'],
            ['id'=>4,'title'=>'流水付',],
        ];
        $secondList          = [
            ['id'=>1,'title'=>'现金'],
            ['id'=>2,'title'=>'承兑汇票'],
        ];
        $result             = [];
        foreach($firstList as $key=>$val)
        {
            $temp           = $val;
            $temp['data']   = $secondList;
            $result[]       = $temp;
        }
        return $result;
    }
}




